package org.linlinjava.litemall.wx.annotation.support;

import org.linlinjava.litemall.wx.annotation.ShopId;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class ShopIdArgumentResolver implements HandlerMethodArgumentResolver {

    public static final String I_LUMIERE_SHOP = "I-Lumiere-Shop";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 只处理带有 @ShopId 注解的参数
        return parameter.hasParameterAnnotation(ShopId.class) && parameter.getParameterType().equals(Integer.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, org.springframework.web.bind.support.WebDataBinderFactory binderFactory) {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        // 从请求头中获取 shopId
        String shopId = request.getHeader(I_LUMIERE_SHOP);

        // 返回解析后的值，如果没有则返回 null
        if (shopId != null) {
            try {
                return Integer.parseInt(shopId);
            } catch (NumberFormatException e) {
                return null; // 如果 shopId 不是整数，则返回 null
            }
        }
        return null;
    }
}
